package com.ledijiaoyu.autogate.packet.response;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import cn.dinkevin.xui.util.StringUtil;

/**
 * Create with Android Studio
 * Author: chengpengfei
 * Date: 2018/5/21
 * Time: 7:40 PM
 * Description: 闸机数据包，本属性值中所有字符串类在转换数据
 */
public class AutoGateResponse {

    public static final char head = 'H';                    // 固定数据包头
    protected String machineCode = "001";                   // 机号，默认为001
    protected String command;                               // 命令
    public static final char tail = 0x0d;                   // 数据包尾

    protected CharBuffer mBuffer = CharBuffer.allocate(200);        // 默认缓存数据长度为 100
    protected int mPoint = 0;

    public static final int POSITION_MACHINE_CODE = 1;
    public static final int POSITION_COMMAND = 4;

    public AutoGateResponse() {}


    public boolean decode(byte[] buffer){

        byte t_head,t_tail;
        if(buffer.length < 1){
            return false;
        }

        char[] t_data = StringUtil.byte2Char(buffer);

        t_head = buffer[0];
        t_tail = buffer[buffer.length - 1];
        if(t_head != head || t_tail != tail){
            return false;
        }

        mBuffer.put(t_data);
        mPoint += t_data.length;

        // 解析机器码
        int point = POSITION_MACHINE_CODE;
        char[] t_temp = new char[]{mBuffer.get(point++),
                        mBuffer.get(point++),
                        mBuffer.get(point++)};
        this.machineCode = StringUtil.char2String(t_temp);

        // 解析 Command
        point = POSITION_COMMAND;
        t_temp = new char[]{mBuffer.get(point++),
                mBuffer.get(point++),
                mBuffer.get(point++),
                mBuffer.get(point++),
                mBuffer.get(point++)};
        this.command = StringUtil.char2String(t_temp);
        return true;
    }


    public String getCommand(){
        return command;
    }
}
